package com.ifinc.common.socket.netty.server;

import com.ifinc.common.socket.netty.ContextConfig;
import com.ifinc.common.socket.simple_netty_server.SimpleMessageFactory;
import com.ifinc.common.socket.simple_netty_server.SimpleMessageHandler;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-5-29
 * Time: 19:48
 */

public class NettyServer {

    ChannelGroup allChannels = new DefaultChannelGroup("time-server");

    private ContextConfig contextConfig;

    public NettyServer(ContextConfig contextConfig) {
        this.contextConfig = contextConfig;
    }

    public ChannelGroup getAllChannels() {
        return allChannels;
    }

    public void setAllChannels(ChannelGroup allChannels) {
        this.allChannels = allChannels;
    }

    public void addChannel(Channel channel){
       allChannels.add(channel);
    }

    private ServerMessageFactory messageFactory;

    @Autowired
    public void setMessageFactory(ServerMessageFactory messageFactory) {
        this.messageFactory = messageFactory;

    }

    public void init() {
        ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool()
                , Executors.newCachedThreadPool(), 500);
        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        bootstrap.setPipelineFactory(messageFactory);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);
        bootstrap.bind(new InetSocketAddress(contextConfig.getPort()));
    }

    public static void startup(){
        ContextConfig contextConfig = new ContextConfig();
        contextConfig.setIp("127.0.0.1");
        contextConfig.setPort(8080);
        contextConfig.setTimeout_conn(10000);
        contextConfig.setTimeout_read(10000);
        contextConfig.setConnection(false);
        ServerMessageHandler simpleMessageHandler = new ServerMessageHandler(contextConfig);
        ServerMessageFactory simpleMessageFactory = new ServerMessageFactory();
        NettyServer simpleNettyServer = new NettyServer(contextConfig);

        simpleMessageFactory.setMessageHandler(simpleMessageHandler);
        simpleNettyServer.setMessageFactory(simpleMessageFactory);
        simpleNettyServer.init();
    }

    public static void main(String[] args) throws Exception {
       startup();
    }
}
